import { Button } from "@renderer/components/ui/base/button";
import { Label } from "@renderer/components/ui/base/field";
import { Modal } from "@renderer/components/ui/base/modal";
import { Textarea } from "@renderer/components/ui/base/textarea";
import type { McpServerType } from "@shared/triplit/types";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";

interface ImportData {
  name: string;
  type: McpServerType;
  url?: string;
  command?: string;
  args?: string[];
  env?: Record<string, string>;
}

interface McpServerImportModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
}

export function McpServerImportModal({
  isOpen,
  onOpenChange,
}: McpServerImportModalProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.mcp-settings.import",
  });
  const navigate = useNavigate();
  const [jsonInput, setJsonInput] = useState("");
  const [isProcessing, setIsProcessing] = useState(false);

  const parseImportData = (jsonText: string): ImportData[] => {
    try {
      const parsed = JSON.parse(jsonText);

      if (!parsed.mcpServers || typeof parsed.mcpServers !== "object") {
        throw new Error("Invalid format: missing mcpServers object");
      }

      const servers: ImportData[] = [];

      for (const [serverName, config] of Object.entries(parsed.mcpServers)) {
        if (typeof config !== "object" || config === null) {
          continue;
        }

        const serverConfig = config as Record<string, unknown>;

        if (serverConfig.url) {
          // URL-based server (streamableHTTP or SSE)
          const url = serverConfig.url as string;
          let type: McpServerType = "streamableHTTP";

          // Determine type based on URL pattern
          if (url.includes("/sse/")) {
            type = "sse";
          } else if (url.includes("/mcp/")) {
            type = "streamableHTTP";
          }

          servers.push({
            name: serverName,
            type,
            url,
          });
        } else if (serverConfig.command && serverConfig.args) {
          // Command-based server (stdio)
          servers.push({
            name: serverName,
            type: "stdio",
            command: serverConfig.command as string,
            args: Array.isArray(serverConfig.args)
              ? (serverConfig.args as string[])
              : [],
            env: (serverConfig.env as Record<string, string>) || {},
          });
        }
      }

      return servers;
    } catch (error) {
      throw new Error(
        `JSON parsing failed: ${error instanceof Error ? error.message : "Unknown error"}`,
      );
    }
  };

  const handleImport = async () => {
    if (!jsonInput.trim()) {
      toast.error(t("error.empty-input"));
      return;
    }

    setIsProcessing(true);

    try {
      const importedServers = parseImportData(jsonInput);

      if (importedServers.length === 0) {
        toast.error(t("error.no-servers-found"));
        return;
      }

      // For now, import the first server (we could extend this to support multiple)
      const serverData = importedServers[0];

      // Navigate to add server page with import data
      const searchParams = new URLSearchParams();
      searchParams.set("import", "true");
      searchParams.set("data", JSON.stringify(serverData));

      navigate(`/settings/mcp-settings/add?${searchParams.toString()}`);
      onOpenChange(false);

      toast.success(t("success", { count: importedServers.length }));
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error";
      toast.error(t("error.parse-failed", { error: errorMessage }));
    } finally {
      setIsProcessing(false);
    }
  };

  const handleClose = () => {
    setJsonInput("");
    onOpenChange(false);
  };

  return (
    <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
      <Modal.Content size="2xl">
        {() => (
          <>
            <Modal.Header>
              <Modal.Title>{t("title")}</Modal.Title>
            </Modal.Header>
            <Modal.Body className="space-y-4">
              <div className="flex flex-col gap-2">
                <Label className="text-fg">{t("json-input.label")}</Label>
                <Textarea
                  value={jsonInput}
                  onChange={setJsonInput}
                  placeholder={`{
  "mcpServers": {
    "302ai-custom-mcp": {
      "command": "npx",
      "args": ["-y", "@302ai/custom-mcp"],
      "env": {"302AI_API_KEY": "sk-xxx"}
    }
  }
}

或者

{
  "mcpServers": {
    "302ai-custom-mcp": {
      "url": "https://api.302.ai/custom-mcp/sse/xxx"
    }
  }
}`}
                  className="min-h-48 resize-none bg-[#F5F5F5] font-mono text-sm dark:bg-[#1A1A1A]"
                />
              </div>
            </Modal.Body>
            <Modal.Footer>
              <Modal.Close onPress={handleClose}>{t("cancel")}</Modal.Close>
              <Button
                onPress={handleImport}
                isPending={isProcessing}
                isDisabled={!jsonInput.trim()}
              >
                {isProcessing ? t("processing") : t("import")}
              </Button>
            </Modal.Footer>
          </>
        )}
      </Modal.Content>
    </Modal>
  );
}
